package com.shanshan.wheel.rpc.common.loadbalance.loadbalancer;

import com.shanshan.wheel.rpc.common.loadbalance.AbstractLoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 轮询均衡
 * @ClassName RoundRobinBalance
 * @Author 山山大魔王
 * @Date 2022/9/4 11:45
 * @Version 1.0
 */
@Slf4j
@Component
public class RoundRobinBalance extends AbstractLoadBalance {

    private static final AtomicInteger atomicInteger = new AtomicInteger();

    private int getAtomicInteger(){
        int expect;
        int update;

        do{
            expect = atomicInteger.get();
            update = expect >= Integer.MAX_VALUE ? 0 : expect + 1;
        }while (atomicInteger.compareAndSet(expect, update));
        return update;
    }

    @Override
    protected String doSelect(List<String> serviceAddress, String rpcServiceName) throws UnknownHostException {
        int index = getAtomicInteger();
        return serviceAddress.get(index % serviceAddress.size());
    }
}
